package com.qm.console.component.util;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.client.RestTemplate;

/**
 * @author chenlei
 * @date 2017/12/7
 */
public class ErrorLogAlarm extends AppenderBase<ILoggingEvent> {
    private static final String DD_URL =
            "https://oapi.dingtalk.com/robot/send?access_token=2280343827dc327b267188e4be6814c9f8b434f83ee1709efa36a5b052bb5762";
    private static final String TEST_DD_URL = "" +
            "https://oapi.dingtalk.com/robot/send?access_token=e033f34a564cfb69ed68aa0c6c44a0aa555027e22aca38a24b1ce32b9f2115be";
    private RestTemplate restTemplate = new RestTemplate();

    @Override
    protected void append(ILoggingEvent eventObject) {

        if (eventObject != null && eventObject.getFormattedMessage() != null) {
            // TODO: 这个类写得比较随意
            // 后面发送钉钉消息这部分，抽出来放到单独的第三方服务里面，这里发送一个异步事件就好了
            new Thread(() -> {
                try {
                    sendDDMsg(eventObject.getFormattedMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    /**
     * send dd msg
     *
     * @param log log
     */
    private void sendDDMsg(String log) {
        String url = TEST_DD_URL;
        log = "[caiqiu]" + log;
        restTemplate.postForObject(url, buildTextMsgBody(log), JSONObject.class);
    }

    /**
     * build text msg body
     *
     * @param log log
     * @return body
     */
    private JSONObject buildTextMsgBody(String log) {
        JSONObject msg = new JSONObject();
        msg.put("msgtype", "text");

        JSONObject text = new JSONObject();
        text.put("content", log);
        msg.put("text", text);

        return msg;
    }
}
